{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "6b41fee0-5ee5-42ea-b751-6f5b3d978fd2",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "from langchain.vectorstores import Chroma\n",
    "from langchain_huggingface import HuggingFaceEmbeddings\n",
    "import os\n",
    "\n",
    "# 定义 Embeddings\n",
    "embeddings = HuggingFaceEmbeddings(model_name=\"m3e-base\")\n",
    "\n",
    "# 向量数据库持久化路径\n",
    "persist_directory = 'data_base/chroma'\n",
    "\n",
    "# 加载数据库\n",
    "vectordb = Chroma(\n",
    "    persist_directory=persist_directory, \n",
    "    embedding_function=embeddings\n",
    ")\n",
    "retriever=vectordb.as_retriever()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "067e1ff2-5390-4a06-9736-2f31a868d5bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ[\"DASHSCOPE_API_KEY\"] = 'sk-***'\n",
    "\n",
    "from langchain_community.llms import Tongyi\n",
    "llm = Tongyi()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "47110d5f-0de4-4dba-9fd9-424f7c9a2321",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\gzwjq\\AppData\\Local\\Temp\\ipykernel_14448\\607710951.py:2: LangChainDeprecationWarning: Please see the migration guide at: https://python.langchain.com/docs/versions/migrating_memory/\n",
      "  memory = ConversationBufferMemory(\n"
     ]
    }
   ],
   "source": [
    "\n",
    "from langchain.memory import ConversationBufferMemory\n",
    "memory = ConversationBufferMemory(\n",
    "    memory_key=\"chat_history\",  # 与 prompt 的输入变量保持一致。\n",
    "    return_messages=True  # 将以消息列表的形式返回聊天记录，而不是单个字符串\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "22030ea2-3414-4431-bfb8-aebcf8fab04e",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    " # 构建新的问答链，使用带有记忆的提示模板\n",
    "\n",
    "from langchain.chains import ConversationalRetrievalChain\n",
    "def chatqwen_chat(message, history):\n",
    "     #构建对话问答链\n",
    "     qa = ConversationalRetrievalChain.from_llm(\n",
    "\t\tllm,\n",
    "\t\tretriever=retriever,\n",
    "\t\tmemory=memory,\n",
    "\t\tverbose=True,\n",
    "\t )\n",
    "     result = qa({\"question\": message})\n",
    "     return result['answer']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "5f656cc7-01da-42bc-a2e4-bc159a5a4298",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "import gradio as gr\n",
    "def launch_gradio():\n",
    "\n",
    "    iface = gr.ChatInterface(\n",
    "        fn=chatqwen_chat,\n",
    "        title=\"金融RAG问答机器人\",\n",
    "        chatbot=gr.Chatbot(height=400),\n",
    "    )\n",
    "    iface.launch(share=True, server_name=\"0.0.0.0\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "bfb9e5c1-2c9a-496e-9cfa-db6354aa6226",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\gzwjq\\.conda\\envs\\langchain_qwen\\lib\\site-packages\\gradio\\components\\chatbot.py:242: UserWarning: You have not specified a value for the `type` parameter. Defaulting to the 'tuples' format for chatbot messages, but this is deprecated and will be removed in a future version of Gradio. Please set type='messages' instead, which uses openai-style dictionaries with 'role' and 'content' keys.\n",
      "  warnings.warn(\n",
      "C:\\Users\\gzwjq\\.conda\\envs\\langchain_qwen\\lib\\site-packages\\gradio\\chat_interface.py:229: UserWarning: The gr.ChatInterface was not provided with a type, so the type of the gr.Chatbot, 'tuples', will be used.\n",
      "  warnings.warn(\n",
      "ERROR:    [Errno 10048] error while attempting to bind on address ('0.0.0.0', 7860): 通常每个套接字地址(协议/网络地址/端口)只允许使用一次。\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "* Running on local URL:  http://0.0.0.0:7861\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\gzwjq\\AppData\\Local\\Temp\\ipykernel_14448\\3178561105.py:12: LangChainDeprecationWarning: The method `Chain.__call__` was deprecated in langchain 0.1.0 and will be removed in 1.0. Use :meth:`~invoke` instead.\n",
      "  result = qa({\"question\": message})\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[1m> Entering new StuffDocumentsChain chain...\u001b[0m\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mUse the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n",
      "\n",
      "financial_dataset\\上海华铭智能终端设备股份有限公司.txt第二节 概览 ..................................................... 23\n",
      "一、发行人简要情况 ....................................................................................... 23\n",
      "二、公司控股股东及实际控制人简介 .............................................................. 25\n",
      "三、发行人的主要财务数据及财务指标 .......................................................... 25financial_dataset\\上海华铭智能终端设备股份有限公司.txt\n",
      "\n",
      "financial_dataset\\上海华铭智能终端设备股份有限公司.txt八、技术与研发情况 ..................................................................................... 150\n",
      "九、境外经营及境外资产情况 ...................................................................... 154\n",
      "十、公司发行当年和未来三年的发展规划及拟采取的措施 ........................... 154\n",
      "第七节 同业竞争与关联交易 ...................................... 160financial_dataset\\上海华铭智能终端设备股份有限公司.txt\n",
      "\n",
      "financial_dataset\\上海华铭智能终端设备股份有限公司.txt股票上市之日起十二个月内，不转让或委托他人管理首次公开发行股票前其持有\n",
      "的发行人股份，也不由发行人回购该部分股份。\n",
      "6、作为公司董事、监事和高级管理人员的股东张亮、谢根方、蔡红梅、冯\n",
      "国祚、陆英、徐剑平、吴立钊、张晓燕、季新华、高彬承诺：在其担任公司董事、\n",
      "监事和高级管理人员期间，每年转让的股份不超过其直接和间接持有发行人股份\n",
      "总数的 25%；离职后六个月内，不转让其直接和间接持有的发行人股份；离职\n",
      "六个月后的十二个月内转让其直接或间接持有的发行人股份不超过该部分股份\n",
      "总数的 50%；在发行人首次公开发行股票上市之日起六个月内申报离职的，自\n",
      "申报离职之日起十八个月内不转让其直接持有的发行人股份；在发行人首次公开\n",
      "发行股票上市之日起第七个月至第十二个月之间申报离职的，自申报离职之日起financial_dataset\\上海华铭智能终端设备股份有限公司.txt\n",
      "\n",
      "financial_dataset\\上海华铭智能终端设备股份有限公司.txt六、主要固定资产及无形资产情况 ............................................................... 145\n",
      "七、公司拥有的特许经营权 .......................................................................... 150\n",
      "八、技术与研发情况 ..................................................................................... 150financial_dataset\\上海华铭智能终端设备股份有限公司.txt\n",
      "\n",
      "Question: 上海华铭智能终端设备股份有限公司的股东有哪些人？\n",
      "Helpful Answer:\u001b[0m\n",
      "\n",
      "Could not create share link. Missing file: C:\\Users\\gzwjq\\.conda\\envs\\langchain_qwen\\lib\\site-packages\\gradio\\frpc_windows_amd64_v0.3. \n",
      "\n",
      "Please check your internet connection. This can happen if your antivirus software blocks the download of this file. You can install manually by following these steps: \n",
      "\n",
      "1. Download this file: https://cdn-media.huggingface.co/frpc-gradio-0.3/frpc_windows_amd64.exe\n",
      "2. Rename the downloaded file to: frpc_windows_amd64_v0.3\n",
      "3. Move the file to this location: C:\\Users\\gzwjq\\.conda\\envs\\langchain_qwen\\lib\\site-packages\\gradio\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div><iframe src=\"http://localhost:7861/\" width=\"100%\" height=\"500\" allow=\"autoplay; camera; microphone; clipboard-read; clipboard-write;\" frameborder=\"0\" allowfullscreen></iframe></div>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mGiven the following conversation and a follow up question, rephrase the follow up question to be a standalone question, in its original language.\n",
      "\n",
      "Chat History:\n",
      "\n",
      "Human: 上海华铭智能终端设备股份有限公司的股东有哪些人？\n",
      "Assistant: 根据提供的信息，可以确认上海华铭智能终端设备股份有限公司的部分股东包括公司的董事、监事和高级管理人员，具体名单如下：\n",
      "\n",
      "- 张亮\n",
      "- 谢根方\n",
      "- 蔡红梅\n",
      "- 冯国祚\n",
      "- 陆英\n",
      "- 徐剑平\n",
      "- 吴立钊\n",
      "- 张晓燕\n",
      "- 季新华\n",
      "- 高彬\n",
      "\n",
      "这些人员作为公司董事、监事和高级管理人员，对其持有的公司股份有特定的转让限制。但请注意，这并不是公司所有股东的完整列表。如果您需要了解完整的股东名单，建议查阅公司的正式公告或相关文件。\n",
      "Follow Up Input: 总共多少人\n",
      "Standalone question:\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new StuffDocumentsChain chain...\u001b[0m\n",
      "\n",
      "\n",
      "\u001b[1m> Entering new LLMChain chain...\u001b[0m\n",
      "Prompt after formatting:\n",
      "\u001b[32;1m\u001b[1;3mUse the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n",
      "\n",
      "financial_dataset\\上海华铭智能终端设备股份有限公司.txt第二节 概览 ..................................................... 23\n",
      "一、发行人简要情况 ....................................................................................... 23\n",
      "二、公司控股股东及实际控制人简介 .............................................................. 25\n",
      "三、发行人的主要财务数据及财务指标 .......................................................... 25financial_dataset\\上海华铭智能终端设备股份有限公司.txt\n",
      "\n",
      "financial_dataset\\上海华铭智能终端设备股份有限公司.txt股票上市之日起十二个月内，不转让或委托他人管理首次公开发行股票前其持有\n",
      "的发行人股份，也不由发行人回购该部分股份。\n",
      "6、作为公司董事、监事和高级管理人员的股东张亮、谢根方、蔡红梅、冯\n",
      "国祚、陆英、徐剑平、吴立钊、张晓燕、季新华、高彬承诺：在其担任公司董事、\n",
      "监事和高级管理人员期间，每年转让的股份不超过其直接和间接持有发行人股份\n",
      "总数的 25%；离职后六个月内，不转让其直接和间接持有的发行人股份；离职\n",
      "六个月后的十二个月内转让其直接或间接持有的发行人股份不超过该部分股份\n",
      "总数的 50%；在发行人首次公开发行股票上市之日起六个月内申报离职的，自\n",
      "申报离职之日起十八个月内不转让其直接持有的发行人股份；在发行人首次公开\n",
      "发行股票上市之日起第七个月至第十二个月之间申报离职的，自申报离职之日起financial_dataset\\上海华铭智能终端设备股份有限公司.txt\n",
      "\n",
      "financial_dataset\\上海华铭智能终端设备股份有限公司.txt四、发行人的控股子公司及参股公司情况 ...................................................... 51\n",
      "五、持有公司5%以上股份的主要股东及实际控制人的基本情况 .................... 52\n",
      "六、发行人股本情况 ....................................................................................... 59\n",
      "七、发行人的股权激励情况 ............................................................................ 61financial_dataset\\上海华铭智能终端设备股份有限公司.txt\n",
      "\n",
      "financial_dataset\\上海华铭智能终端设备股份有限公司.txt四、发行人的控股子公司及参股公司情况 ...................................................... 51\n",
      "五、持有公司5%以上股份的主要股东及实际控制人的基本情况 .................... 52\n",
      "六、发行人股本情况 ....................................................................................... 59\n",
      "七、发行人的股权激励情况 ............................................................................ 61financial_dataset\\上海华铭智能终端设备股份有限公司.txt\n",
      "\n",
      "Question: 上海华铭智能终端设备股份有限公司的股东总共有多少人？\n",
      "Helpful Answer:\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n",
      "\n",
      "\u001b[1m> Finished chain.\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "\n",
    "# 启动 Gradio 服务\n",
    "launch_gradio()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "523c190f-1472-4905-af9b-c6454b96f4a2",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "langchain_qwen",
   "language": "python",
   "name": "langchain_qwen"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
